﻿#pragma once
#include <QHttpServerResponse>
#include <QObject>
#include <QProtobufSerializer>
#include <QWebSocketServer>
#include "ShowWidget.h"
#include "message_storage.qpb.h"
#include "message_transmit.qpb.h"
#include "user.qpb.h"
using namespace chat;
//////////////////////////////////////////////
/// 实现 socket 通信
//////////////////////////////////////////////
class WebSocket : public QObject
{
    Q_OBJECT
public:
    static WebSocket* get_instance();
    bool              init();
private:
    const static int  WEB_SOCKET_PORT = 9001;  // WebSocket 端口
    static WebSocket* instance;
    WebSocket();
    WebSocket(const WebSocket&)            = delete;
    WebSocket& operator=(const WebSocket&) = delete;
    ~WebSocket();
private:
    /* 工具方法 */
    QByteArray                   read_file(const QString& file_name);
    qint64                       get_current_time_stamp();
    QHttpServerResponse          make_http_response(const QByteArray& data);
    std::unique_ptr<UserInfo>    make_user_info(const QByteArray& avatar, const QString& user_id,
                                                const QString& description, const QString& nick_name, const QString& phone);
    std::unique_ptr<MessageInfo> make_message_info(int index, const QString& chat_session_id, const QString& user_id, const QByteArray& avatar);
    std::unique_ptr<MessageInfo> make_image_info(int index, const QString& chat_session_id, const QString& user_id, const QByteArray& avatar);
    std::unique_ptr<MessageInfo> make_file_info(int index, const QString& chat_session_id, const QString& user_id, const QByteArray& avatar);
    std::unique_ptr<MessageInfo> make_speech_info(int index, const QString& chat_session_id, const QString& user_id, const QByteArray& avatar);
signals:
    void send_txt_message();                     // 发送文本消息给客户端, 当点击按钮时会发送
    void delete_friend();                        // 删除好友, 当点击按钮时会发送
    void send_friend_apply();                    // 发送好友申请, 当点击按钮时会发送
    void send_friend_apply_process(bool agree);  // 是否同意好友申请, 当点击按钮时会发送
    void send_create_group();                    // 创建群组, 当点击按钮时会发送
    void send_image_message();                   // 发送图片消息给客户端, 当点击按钮时会发送
    void send_file_message();                    // 发送文件消息给客户端, 当点击按钮时会发送
    void send_speech_message();                  // 发送语音消息给客户端, 当点击按钮时会发送
private:
    QWebSocketServer    socket_server;
    ShowWidget*         show_widget;
    int                 index = 1;  // 用于累加消息索引
    QProtobufSerializer serializer;
};